package com.xiedafeng.www.proxy;

import com.xiedafeng.www.exception.DatabaseException;
import com.xiedafeng.www.exception.LoginException;
import com.xiedafeng.www.exception.PermissionException;
import com.xiedafeng.www.exception.ReflectException;
import com.xiedafeng.www.po.User;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ServiceProxy implements InvocationHandler {
    private Object target;
    public ServiceProxy(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            return method.invoke(target, args);
        }
        catch (InvocationTargetException invocationTargetException){
            Logger logger=Logger.getLogger("com.xiedafeng.www.proxy.ServiceProxy");
            if (invocationTargetException.getTargetException() instanceof LoginException) {
                logger.log(Level.INFO,"登录失败！");
                return (List<User>) new ArrayList();
            }
            else if (invocationTargetException.getTargetException() instanceof ReflectException){
                logger.log(Level.INFO,((ReflectException) invocationTargetException.getTargetException()).getErrorMessage());
                return null;
            }
            else if (invocationTargetException.getTargetException() instanceof DatabaseException){
                logger.log(Level.INFO,((ReflectException) invocationTargetException.getTargetException()).getErrorMessage());
                return null;
            }
            else if (invocationTargetException.getTargetException() instanceof PermissionException){
                User user=(User)args[0];
                List<User> userList=new ArrayList<>();
                userList.add(user);
                logger.log(Level.INFO,"用户{0}请求创建瓜圈失败！",new Object[]{user.getName()});
                return userList;
            }
        }
        return null;
    }
}
